package com.agileai.miscdp.hotweb.ui.wizards;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.agileai.miscdp.hotweb.database.DBManager.DataBaseType;
import com.agileai.miscdp.util.MiscdpUtil;
import com.ibatis.common.jdbc.ScriptRunner;
import com.agileai.common.IniReader;
/**
 * Hotweb工程向导数据连接配置页
 */
public class HotwebProjectWizardConfigPage extends WizardPage {
	private Text userPwdText;
	private Text userIdText;
	private Text driverUrlText;
	private Text driverClassText;
	private Button mysqlRadioButton;
	private Button oracleRadioButton;
	private Button sqlServerRadioButton;
	private HotwebProjectWizard wizard = null;
	Button initialDataButton = null;
	boolean defaultPageComplete = false;
	
	public Text getUserPwdText() {
		return userPwdText;
	}
	public Text getUserIdText() {
		return userIdText;
	}
	public Text getDriverUrlText() {
		return driverUrlText;
	}
	
	public Text getDriverClassText() {
		return driverClassText;
	}
	
	public HotwebProjectWizardConfigPage(HotwebProjectWizard wizard) {
		super("");
		IniReader reader = MiscdpUtil.getIniReader(); 
		String title = reader.getValue("ProjectWizard","CfgWizardTitle");
		setTitle(title);
		this.wizard = wizard;
		String desc = reader.getValue("ProjectWizard","CfgWizardDesc");
		setDescription(desc);
	}
	
	private Properties getInitialProperties(String databaseType){
		Properties properties = new Properties();
		if (DataBaseType.MySQL.equals(databaseType)){
			properties.setProperty("DatabaseConfig.ConnectURL", "jdbc:mysql://localhost:3306/DabaseName");
			properties.setProperty("DatabaseConfig.UserName", "root"); 
			properties.setProperty("DatabaseConfig.UserPassword", "root");
			properties.setProperty("DatabaseConfig.DriverClass", "com.mysql.jdbc.Driver");			
		}else if (DataBaseType.Oracle.equals(databaseType)){
			properties.setProperty("DatabaseConfig.ConnectURL", "jdbc:oracle:thin:@localhost:1521:SID");
			properties.setProperty("DatabaseConfig.UserName", ""); 
			properties.setProperty("DatabaseConfig.UserPassword", "");
			properties.setProperty("DatabaseConfig.DriverClass", "oracle.jdbc.driver.OracleDriver");
		}
		else {
			properties.setProperty("DatabaseConfig.ConnectURL", "jdbc:jtds:sqlserver://localhost:1433/DabaseName");
			properties.setProperty("DatabaseConfig.UserName", "sa"); 
			properties.setProperty("DatabaseConfig.UserPassword", "");
			properties.setProperty("DatabaseConfig.DriverClass", "net.sourceforge.jtds.jdbc.Driver");
		}
		return properties;
	}
	
	public void createControl(Composite parent) {
		Label driverclassLabel;
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		layout.marginWidth = 3;
		container.setLayout(layout);
		layout.numColumns = 2;
		layout.verticalSpacing = 3;
		
		Label databaseTypeLabel = new Label(container, SWT.NONE);
		databaseTypeLabel.setText(Messages.getString("DatabaseType"));
		
		Composite composite_1 = new Composite(container, SWT.NONE);
		composite_1.setLayout(new GridLayout(3, false));
		
		mysqlRadioButton = new Button(composite_1, SWT.RADIO);
		mysqlRadioButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Properties properties = getInitialProperties(DataBaseType.MySQL);
				userPwdText.setText(properties.getProperty("DatabaseConfig.UserPassword"));
				userIdText.setText(properties.getProperty("DatabaseConfig.UserName"));
				driverUrlText.setText(properties.getProperty("DatabaseConfig.ConnectURL"));
				driverClassText.setText(properties.getProperty("DatabaseConfig.DriverClass"));
			}
		});
		mysqlRadioButton.setSelection(true);
		mysqlRadioButton.setText("MySQL");
		
		oracleRadioButton = new Button(composite_1, SWT.RADIO);
		oracleRadioButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Properties properties = getInitialProperties(DataBaseType.Oracle);
				userPwdText.setText(properties.getProperty("DatabaseConfig.UserPassword"));
				userIdText.setText(properties.getProperty("DatabaseConfig.UserName"));
				driverUrlText.setText(properties.getProperty("DatabaseConfig.ConnectURL"));
				driverClassText.setText(properties.getProperty("DatabaseConfig.DriverClass"));
			}
		});
		oracleRadioButton.setText("Oracle");
		
		sqlServerRadioButton = new Button(composite_1, SWT.RADIO);
		sqlServerRadioButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Properties properties = getInitialProperties(DataBaseType.SQLServer);
				userPwdText.setText(properties.getProperty("DatabaseConfig.UserPassword"));
				userIdText.setText(properties.getProperty("DatabaseConfig.UserName"));
				driverUrlText.setText(properties.getProperty("DatabaseConfig.ConnectURL"));
				driverClassText.setText(properties.getProperty("DatabaseConfig.DriverClass"));
			}
		});
		sqlServerRadioButton.setText("SQLServer");
		
		driverclassLabel = new Label(container, SWT.NULL);
		driverclassLabel.setText(Messages.getString("ConnectionDriverClass"));
		
		driverClassText = new Text(container, SWT.BORDER | SWT.SINGLE);
		driverClassText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validateDialog();
			}
		});
		driverClassText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		
		final Label driverurlLabel = new Label(container, SWT.NULL);
		driverurlLabel.setText(Messages.getString("ConnectionURL"));
		
		driverUrlText = new Text(container, SWT.BORDER | SWT.SINGLE);
		driverUrlText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validateDialog();
			}
		});
		driverUrlText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		final Label userIdLabel = new Label(container, SWT.NONE);
		userIdLabel.setText(Messages.getString("ConnectionUserName"));

		userIdText = new Text(container, SWT.BORDER);
		userIdText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validateDialog();
			}
		});
		userIdText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

		final Label userPwdLabel = new Label(container, SWT.NONE);
		userPwdLabel.setText(Messages.getString("ConnectionUserPwd"));

		userPwdText = new Text(container, SWT.BORDER | SWT.PASSWORD);
		userPwdText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				validateDialog();
			}
		});
		userPwdText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		new Label(container, SWT.NONE);
		
		setControl(container);
		
		Composite composite_2 = new Composite(container, SWT.NONE);
		composite_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		composite_2.setLayout(new GridLayout(2, false));
		
		final Button testButton = new Button(composite_2, SWT.NONE);
		testButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (validateDialog()){
					String driverClass = getDriverClassText().getText();
					String driverUrl = getDriverUrlText().getText();
					String userId = getUserIdText().getText();
					String userPwd = getUserPwdText().getText();
					String[] driverJars = MiscdpUtil.getDriverJarArray(getDataBaseType());
					if (!MiscdpUtil.isValidConnection(driverClass,driverUrl,userId,userPwd,driverJars)){
						MessageDialog.openInformation(getShell(),"提示信息","不能连接，请确认数据库连接信息填写正确！");
					}else{
						setPageComplete(true);
						if (wizard.basePage.serviceWebRadioButton.getSelection()){
							initialDataButton.setEnabled(false);
						}else{
							initialDataButton.setEnabled(true);			
						}
						MessageDialog.openInformation(getShell(),"OK","数据连接成功!");	
					}
				}
			}
		});
		testButton.setText("测试连接");
		
		initialDataButton = new Button(composite_2, SWT.NONE);
		initialDataButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String databaseType = getDataBaseType();
				String driverClass = getDriverClassText().getText();
				String driverUrl = getDriverUrlText().getText();
				String userId = getUserIdText().getText();
				String userPwd = getUserPwdText().getText();
				testButton.setEnabled(false);
				setPageComplete(false);
				try {
					executeSQL(databaseType, driverClass, driverUrl, userId, userPwd);
					MessageDialog.openInformation(getShell(),"OK","数据库初始化成功!");
				} catch (Exception e2) {
					MessageDialog.openInformation(getShell(),"Fail","数据库初始化失败!");
				}
				testButton.setEnabled(true);
				setPageComplete(true);
			}
		});
		initialDataButton.setText(Messages.getString("InitialData"));
		initialDataButton.setEnabled(false);
		initialize();
		this.setPageComplete(defaultPageComplete);
	}
	private void executeSQL(String databaseType,String driver,String url,String username,String password)  throws Exception{
		try {
			Class.forName(driver).newInstance();
			Connection conn = (Connection) DriverManager.getConnection(url,
					username, password);
			ScriptRunner runner = new ScriptRunner(conn,false, false);
			File scriptFile = MiscdpUtil.getInitSQLFile(databaseType);
			Reader reader = new FileReader(scriptFile);
			runner.runScript(reader);
		} catch (Exception e) {
			throw e;
		}
	}
	private void initialize() {
		Properties properties = getInitialProperties(DataBaseType.MySQL);
		userPwdText.setText(properties.getProperty("DatabaseConfig.UserPassword"));
		userIdText.setText(properties.getProperty("DatabaseConfig.UserName"));
		driverUrlText.setText(properties.getProperty("DatabaseConfig.ConnectURL"));
		driverClassText.setText(properties.getProperty("DatabaseConfig.DriverClass"));
	}

	public String getDataBaseType(){
		String databaseType =  null;
		if (mysqlRadioButton.getSelection()){
			databaseType = DataBaseType.MySQL;
		}
		else if (oracleRadioButton.getSelection()){
			databaseType = DataBaseType.Oracle;
		}
		else if (sqlServerRadioButton.getSelection()){
			databaseType = DataBaseType.SQLServer;
		}
		return databaseType;
	}
	
	private boolean validateDialog() {
		String userId = this.userIdText.getText().trim();
		String userPwd = this.userPwdText.getText().trim();
		String driverClass = this.driverClassText.getText().trim();
		String driverUrl = this.driverUrlText.getText().trim();
		initialDataButton.setEnabled(false);
		
		if (userId.length() == 0) {
			updateStatus("userName must be specified !");
			return false;
		}
		if (userPwd.length() == 0) {
			updateStatus("userPwd must be specified !");
			return false;
		}
		if (driverClass.length() == 0) {
			updateStatus("driverClass must be specified !");
			return false;
		}
		if (driverUrl.length() == 0) {
			updateStatus("driverUrl must be specified !");
			return false;
		}
		updateStatus(null);
		return true;
	}
	private void updateStatus(String message) {
		setErrorMessage(message);
	}
}